package cool.mor.config;

import cool.mor.dao.UserRepository;
import cool.mor.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Ivan
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserRepository userRepository;
    /**
     * 授权功能
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了Realm的授权方法");
        return null;
    }

    /**
     * 认证功能
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了Realm的认证方法");

        //调取之前controller中的UsernamePasswordToken 拿到前端输入的用户名
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        System.out.println("userToken--------->"+userToken);
        User user = userRepository.findByPhoneNumber(userToken.getUsername());
        if (user==null){
            return null;
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
